<template>
	<view class="page" :style="{paddingTop: `${topHeight}px`}" style="height: 95vh;">
		<!--头部-->
		<!-- <view class="header">
			<view class="h-l">
			</view>
			<view class="h-c">
			</view>
			<view class="h-r">
				<uni-icons type="closeempty" size="26" @click="handleClose"></uni-icons>
			</view>
		</view> -->
		<!--照片预览-->
		<view class="content" style="height: 95vh;">
			<!-- 水印相机拍照后页面 隐藏在底层（为了处理添加水印 因为父页面为nvue页面，画布添加不了水印）style="height: 0;"-->
			<view class="image-preview">
				<!-- <view>拍摄结果预览图</view> -->
				<!-- <view v-if="loading" class="loading">
					<image src="/static/loading.gif" style="width: 100rpx;height: 100rpx;"></image>
				</view> -->
				<view class="img-item" @click="lookImg(imgUrl)">
					<image :src="imgUrl" style="width: 100%; height: 100%;"></image>
				</view>
			</view>
			<view class="menu">
				<view class="save-switch" v-if="source !== 'QrCodePhotoUpload'">
					<text style="color: #fff;">同时保存到手机相册</text>
					<switch @change="switchChange" :checked="saveToAlbum" color="#3f85ff" style="transform:scale(0.8)"/>
				</view>
				<view style="border-bottom: 0.5px solid gray;flex: 0 0 auto;"></view>
				<view class="save-btn">
					<view class="circle1" @click="handleClose">
						<image src="/static/watermark-camera/chexiao.svg" style="width: 50rpx;height:50rpx;"></image>
					</view>
					<view class="circle2" @click="saveImageToAlbum">
						<image src="/static/watermark-camera/duigou.svg" style="width: 50rpx;height:50rpx;"></image>
					</view>
				</view>
			</view>
		</view>
		<canvas id="canvas-clipper" canvas-id="canvas-clipper" type="2d"
			:style="{width: canvasSiz.width+'px',height: canvasSiz.height+'px',position: 'absolute',left:'-500000px',top: '-500000px'}" />
	</view>
</template>

<script>
	import { getCurrentInstance} from "vue";
  import { useUserStore } from '@/pinia-store/user'
  import { COMMON_API_BASE_URL } from '@/utils/request'
  import { mapStores } from 'pinia'
	var _this;
	export default {
		data() {
			return {
				topHeight: 0,
				loadEnd:false,//图片水印是否加载完成
				imgUrl:'',
				canvasSiz: {
					width: 0,
					height: 0
				},
				snapshotInfo:{},
        source:'', // 来源
        id:'', // 审批单id
        saveToAlbum: true,
        itemId:'', // 起码组件还是止码组件
        apply_id:'', // 起码组件还是止码组件
        component_id:'', // 起码组件还是止码组件
        token:'',
        qrToken:'',
			}
		},
    computed: {
      ...mapStores(useUserStore)
    },
		created() {
      uni.showLoading({ title: '加载中...',mask:true });
			_this = this;
			let app = uni.getSystemInfoSync();
			_this.topHeight = app.statusBarHeight;

			const instance = getCurrentInstance().proxy;
			const eventChannel = instance.getOpenerEventChannel();
			//拍照后添加水印（普通水印）
			eventChannel.on('snapshotInfo', async function(data) {
				//console.log("more==snapshotInfo===", data)
				_this.snapshotInfo = data.snapshot;
				_this.watermark(data.snapshot);
			});
		},
    onLoad (e) {
      this.source = e?.source || ''
      this.id = e?.id || ''
      this.itemId = e?.itemId || ''
      this.apply_id = e?.apply_id || ''
      this.component_id = e?.component_id || ''
      this.qrToken = e?.qrToken || ''
      if(e?.source){
        this.saveToAlbum = false
      }
    },
    mounted () {
      this.token = this.userStore.user.token;
    },
		methods: {
      switchChange(e) {
        this.saveToAlbum = e.detail.value
      },
			handleClose() {
				uni.navigateBack({ delta: 1 });
			},
			//添加照片水印
			watermark(info) {
				_this.savePhoto(info.path);
			  	//console.log("获取到的数据为", info);
			  	uni.getImageInfo({
			  		src: info.path,
			  		success: function(image) {
			  			//console.log(image);
			  			_this.canvasSiz.width = image.width;
			  			_this.canvasSiz.height = image.height;
			  			let maxWidth = image.width;
			  			setTimeout(() => {
			  				let ctx = uni.createCanvasContext('canvas-clipper', _this);
			  				ctx.drawImage(
			  					info.path,
			  					0,
			  					0,
			  					image.width,
			  					image.height
			  				);
			  				//具体位置和相机页面上一致！！！！
							// #ifdef APP-PLUS
							_this.addRemind(ctx, image, info);
							// #endif
							// #ifdef H5
							_this.addRemindH5(ctx, image, info);
							// #endif
			  				ctx.draw(false, () => {
			  					uni.canvasToTempFilePath({
			  							destWidth: image.width,
			  							destHeight: image.height,
			  							canvasId: 'canvas-clipper',
			  							fileType: 'jpg',
			  							success: function(res) {
											//console.log("res=====", res)
											//保存图片，方便核查
											_this.savePhoto(res.tempFilePath);
											_this.loadEnd = true;
                      uni.hideLoading();
			  							},fail:function(){
                        uni.hideLoading();
                      }
			  						},
			  						_this
			  					);
			  				});
			  			}, 100)
			  		},fail:function(){
              uni.hideLoading();
            }
			  	});
			},
			addRemind(ctx, image, info) {
				let x=50,y=image.height-400,w=700,h=410,r=10;
				//水印 时分
				ctx.font = 'bold 70px Arial'; // 设置字体大小和类型
				ctx.fillStyle = '#fff'; // 设置文本颜色
				ctx.shadowOffsetX = 2;   // 水平方向阴影偏移量
				ctx.shadowOffsetY = 2;   // 垂直方向阴影偏移量
				ctx.shadowBlur = 5;      // 阴影模糊程度
				ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; // 阴影颜色及透明度
				ctx.fillText(info.info.dateHm, x, y+70);
				//水印 年月日
				ctx.font = 'bold 35px Arial'; // 设置字体大小和类型
				ctx.fillText(info.info.dateYmd, x, y+120);
				//水印 竖线
				ctx.moveTo(x+220, y+20);
				ctx.lineTo(x+220, y+120);
				ctx.lineWidth = 8;
				ctx.closePath();
				ctx.strokeStyle = '#fff';
				ctx.stroke();
				ctx.fill();
				let addressArr = [];
				//截取地址，换行
				_this.captureAddress(info.info.address, addressArr);
				let yNew = 0;
				if(addressArr.length == 1) {
					yNew = y + 20;
				}else if(addressArr.length == 2) {
					yNew = y + 10;
				}else if(addressArr.length == 3) {
					yNew = y;
				}
				//水印 打卡签到人
				ctx.fillText("签到打卡·"+info.info.workerName, x+240, yNew);
				//水印 定位地址
				ctx.drawImage('/static/icon/zuobiaoWhite.png', x+240, yNew+20, 35, 35);
				ctx.fillText(addressArr[0], x+280, yNew+50);
				if(addressArr.length == 2) {
					ctx.fillText(addressArr[1], x+280, yNew+100);
				}else if(addressArr.length == 3) {
					ctx.fillText(addressArr[1], x+280, yNew+100);
					ctx.fillText(addressArr[2], x+280, yNew+150);
				}
			},
			addRemindH5(ctx, image, info) {
				let x=30,y=image.height-150,w=700,h=410,r=10;
				//水印 时分
				ctx.font = 'bold 26px Arial'; // 设置字体大小和类型
				ctx.fillStyle = '#fff'; // 设置文本颜色
				ctx.shadowOffsetX = 2;   // 水平方向阴影偏移量
				ctx.shadowOffsetY = 2;   // 垂直方向阴影偏移量
				ctx.shadowBlur = 5;      // 阴影模糊程度
				ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; // 阴影颜色及透明度
				ctx.fillText(info.info.dateHm, x, y+70);
				//水印 年月日
				ctx.font = 'bold 13px Arial'; // 设置字体大小和类型
				ctx.fillText(info.info.dateYmd, x, y+90);
				//水印 竖线
				ctx.moveTo(x+80, y+50);
				ctx.lineTo(x+80, y+90);
				ctx.lineWidth = 4;
				ctx.closePath();
				ctx.strokeStyle = '#fff';
				ctx.stroke();
				ctx.fill();
				let addressArr = [];
				//截取地址，换行
				_this.captureAddress(info.info.address, addressArr);
				let yNew = 0;
				if(addressArr.length == 1) {
					yNew = y + 65;
				}else if(addressArr.length == 2) {
					yNew = y + 55;
				}else if(addressArr.length == 3) {
					yNew = y + 45;
				}
				//水印 打卡签到人
				ctx.fillText("签到打卡·"+info.info.workerName, x+90, yNew);
				//水印 定位地址
				ctx.drawImage('/static/icon/zuobiaoWhite.png', x+90, yNew+10, 14, 14);
				ctx.fillText(addressArr[0], x+105, yNew+20);
				if(addressArr.length == 2) {
					ctx.fillText(addressArr[1], x+105, yNew+40);
				}else if(addressArr.length == 3) {
					ctx.fillText(addressArr[1], x+105, yNew+40);
					ctx.fillText(addressArr[2], x+105, yNew+60);
				}
			},
			//保存图片，方便核查
			savePhoto(path) {
				_this.imgUrl = path;
			},
			lookImg(path) {
			  	// 预览图片
			  	uni.previewImage({
			  		current: 0,
			  		urls: [_this.imgUrl],
			  	});
			},
			//保存图片到手机相册
			saveImageToAlbum() {
        if(!_this.loadEnd) {
          uni.showToast({
            title: '稍等一下，还没有准备好！',
            icon:'none',
          });
          return
        };

        if (!_this.saveToAlbum) {
          if(_this.source == 'QrCodePhotoUpload'){
            uni.navigateBack({
              delta: 2,
              success: function (res) {
                uni.$emit('updateMileagePhoto', {
                  imgurl:_this.imgUrl,
                  itemId:_this.itemId
                })
              }
            })
          } else if(_this.source == 'homeIndex' || _this.source == 'h5homeIndex'){
            _this.setapplyUploadPhoto(_this.source)
          } else {
            _this.handleClose();
          }
          return;
        }

				// if(_this.loadEnd) {
					// #ifdef APP-PLUS
					uni.saveImageToPhotosAlbum({
						filePath: _this.imgUrl,
						success: async function (path) {
              await uni.$u.toast('保存成功，请至手机相册查看');
							//console.error('保存相册成功',path);
              if(_this.source == 'QrCodePhotoUpload'){
                uni.navigateBack({
                  delta: 2,
                  success: function (res) {
                    uni.$emit('updateMileagePhoto', {
                      imgurl:_this.imgUrl,
                      itemId:_this.itemId
                    })
                  }
                })
              } else if(_this.source == 'homeIndex' || _this.source == 'h5homeIndex'){
                await _this.setapplyUploadPhoto()
              } else{
                _this.handleClose();
              }
						},
						fail: function (error) {
							//console.error('保存失败', error);
							uni.$u.toast('保存失败，请重新拍摄');
						}
					});
					// #endif
					// #ifdef H5
					//var image = _this.imgUrl;
					/*const blob = _this.base64ToBlob(_this.imgUrl);
					var link = document.createElement('a');
					link.href = URL.createObjectURL(blob);
					link.download = 'image-'+_this.snapshotInfo.info.dateYmdhms+'.png';
					//document.body.appendChild(link);
					link.click();
					link.remove();*/
					const script = document.createElement('script');
					script.src = 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js';
					script.onload = () =>{
						//console.log("123====",_this.imgUrl);
						saveAs(_this.imgUrl, 'image-'+_this.snapshotInfo.info.dateYmdhms+'.png');
					};
					document.head.appendChild(script);

          if(_this.source == 'QrCodePhotoUpload'){
            uni.navigateBack({
              delta: 2,
              success: function (res) {
                uni.$emit('updateMileagePhoto', {
                  imgurl:_this.imgUrl,
                  itemId:_this.itemId
                })
              }
            })
          }else if(_this.source == 'homeIndex' || _this.source == 'h5homeIndex'){
             _this.setapplyUploadPhoto()
          }
					// #endif
				// }
			},
			base64ToBlob(base64) {
				const byteString = atob(base64.split(',')[1]);
			    const mimeString = base64.split(',')[0].split(':')[1].split(';')[0];
			    const ab = new ArrayBuffer(byteString.length);
			    const ia = new Uint8Array(ab);
			    for (let i = 0; i < byteString.length; i++) {
					ia[i] = byteString.charCodeAt(i);
			    }
			    return new Blob([ab], { type: mimeString });
			},
			//截取地址 每12个字符放一行
			captureAddress(address, addressArr) {
				if(address) {
					let arr = Array.from(address);
					let addressStr1 = '';
					let addressStr2 = '';
					let addressStr3 = '';
					arr.forEach((item, index)=>{
						if(index < 12) {
							addressStr1 += item;
						}else if(index >= 12 && index < 24) {
							addressStr2 += item;
						}else if(index >= 24 && index < 35) {
							addressStr3 += item;
						}else {
							addressStr3 += '...';
						}
					});
					if(addressStr1) {
						addressArr.push(addressStr1);
					}
					if(addressStr2) {
						addressArr.push(addressStr2);
					}
					if(addressStr3) {
						addressArr.push(addressStr3);
					}
				}
			},
      async setapplyUploadPhoto(value){
        let delta = value == 'homeIndex' ? 2 : 3
        uni.showLoading({ title: '上传中...', mask: true });
          try {
            const tempFilePath = this.base64ToTempFilePath(this.imgUrl);
            const res = await uni.uploadFile({
              url: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/form/QrCode/uploadPhoto`,
              filePath: tempFilePath,
              name: 'file',
              formData: {
                apply_id: _this.apply_id || '',
                component_id: _this.component_id || '',
                token: _this.token || '',
                qrToken:_this.qrToken || ''
              },
            });

            const data = JSON.parse(res.data);

            if (data.status == 1) {
              uni.hideLoading();
              uni.showToast({
                title: data.msg || '上传成功',
                icon: 'success',
                duration: 2000
              });

              setTimeout(()=>{
                uni.navigateBack({ delta: delta});
              },500)
            } else {
              uni.hideLoading();
              uni.showToast({
                title: data.msg || '上传失败，请稍后重试',
                icon: 'none',
                duration: 2000
              });
            }
          } catch (error) {
            uni.hideLoading();
            uni.showToast({
              title: '上传失败，请稍后重试',
              icon: 'none',
              duration: 1000
            });
            console.error('上传错误:', error);
          }
      },
      base64ToTempFilePath(base64Data) {
        // #ifdef APP-PLUS
          return base64Data
        // #endif

        // #ifdef H5
          const base64WithoutPrefix = base64Data.replace(/^data:image\/\w+;base64,/, '');
          const byteCharacters = atob(base64WithoutPrefix);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
              byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);
          const blob = new Blob([byteArray], { type: 'image/png' });

          const tempUrl = URL.createObjectURL(blob);

          return tempUrl
        // #endif
      }
		}
	}
</script>

<style lang="scss" scoped>
	page {
		padding-bottom: 50rpx;
		overflow: hidden;
	}
	.header {
		position: relative;
		z-index: 9999;
		padding: 20rpx 22rpx;
		display: flex;
		align-items: center;
		.h-l {
			width: 30%;
			display: flex;
			flex-direction: row;
			gap: 20rpx;
		}
		.h-c {
			width: 40%;
			text-align: center;
		}
		.h-r {
			width: 30%;
			display: flex;
			justify-content: flex-end;
		}
	}
	.content {
		height: 90vh;
		display: flex;
		flex-direction: column;
		.image-preview {
			flex: 1 1 auto;
			background-color: #909399;
			.loading {
				display: flex;
				height: 100%;
				justify-content: center;
				align-items: center;
			}
			.img-item {
				display: flex;
				height: 100%;
			}
		}
		.menu {
			height: 500rpx;
			flex: 0 0 auto;
			background-color: #000;
			display: flex;
			flex-direction: column;
			.save-switch {
				flex:0 0 auto;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx;
			}
			.save-btn {
				flex: 1 1 auto;
				display: flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
				gap: 200rpx;
				.circle1 {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					background: #909399;
					display: flex;
					justify-content: center;
					align-items: center;
				}
				.circle2 {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					background-color: #fff;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
	}
</style>
